// 2017-08-11 为去阳江旅游准备的抽奖程序
var fs = require('fs')
var url = require('url')
var path = require('path')
var http = require('http')
var querystring = require('querystring')

function runServer () {
  var mime = {
    'html': 'text/html',
    'js': 'text/javascript',
    'json': 'application/json'
  }

  http.createServer((req, res) => {
    var parseURL = url.parse(req.url)
    var pathname = parseURL.pathname
    var query = querystring.parse(parseURL.query)
    if (/\/$/.test(pathname)) {
      pathname = pathname + 'index.html'
    }

    if (pathname === '/del') {
      var name = query.name
      var text = JSON.parse(fs.readFileSync('./data.json', {encoding: 'utf-8'})  || '[]')
      var index = text.indexOf(name)
      text.splice(index, 1)
      fs.writeFileSync('./data.json', JSON.stringify(text))

      res.writeHead(200, { 'Content-Type': 'text/plain' })
      res.write('success', 'binary')
      res.end()
      return
    }

    if (pathname === '/win') {
      var name = query.name
      var text = JSON.parse(fs.readFileSync('./win.json', {encoding: 'utf-8'})  || '[]')
      text.push(name)
      fs.writeFileSync('./win.json', JSON.stringify(text))

      res.writeHead(200, { 'Content-Type': 'text/plain' })
      res.write('success', 'binary')
      res.end()
      return
    }

    if (pathname === '/add') {
      var name = query.name
      var text = JSON.parse(fs.readFileSync('./data.json', {encoding: 'utf-8'})  || '[]')
      text.push(name)
      fs.writeFileSync('./data.json', JSON.stringify(text))

      res.writeHead(200, { 'Content-Type': 'text/plain' })
      res.write('success', 'binary')
      res.end()
      return
    }

    if (pathname === '/reset') {
      var name = query.name
      fs.writeFileSync('./win.json', '[]')

      res.writeHead(200, { 'Content-Type': 'text/plain' })
      res.write('success', 'binary')
      res.end()
      return
    }

    var ext = path.extname(pathname)
    var realPath = '.' + pathname
    ext = ext ? ext.slice(1) : 'unknown'
    var contentType = mime[ext] || 'text/plain'

    fs.stat(realPath, (err, stats) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/plain' })
        res.write('This request URL ' + pathname + ' was not found on this server.')
        res.end()
      } else {
        fs.readFile(realPath, 'binary', function (err, file) {
          if (err) {
            res.writeHead(500, { 'Content-Type': 'text/plain' })
            res.end(err.message)
          } else {
            res.writeHead(200, { 'Content-Type': contentType })
            res.write(file, 'binary')
            res.end()
          }
        })
      }
    })
  }).listen(8090)
}

runServer()

console.log('Server run on port: 8090')